from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from goods.models import Brand


class BrandSerializer(ModelSerializer):
    class Meta:
        model = Brand
        fields = '__all__'
        read_only_fields = ('logo',)

    def create(self, validated_data):
        # 重写创建对象方法，ＵＲＬ图片需要传到ｆｓｄｒｆ服务器
        file = self.context['request'].FILES.get('logo')
        file_bin = file.read()
        # 创建FastDFS客户端实例
        client = Fdfs_client(settings.FDFS_CONFIG_DIRS)
        # 调用FastDFS客户端上传文件方法
        ret = client.upload_by_buffer(file_bin)
        if ret['Status'] != 'Upload successed.':
            raise serializers.ValidationError('上传图片失败')
        brand = Brand.objects.create(
            name=validated_data['name'],
            first_letter=validated_data['first_letter'],
            logo=ret['Remote file_id']
        )
        return brand

    def update(self, instance, validated_data):
        # 重写创建对象方法，ＵＲＬ图片需要传到ｆｓｄｒｆ服务器
        file = self.context['request'].FILES.get('logo')
        file_bin = file.read()
        # 创建FastDFS客户端实例
        client = Fdfs_client(settings.FDFS_CONFIG_DIRS)
        # 调用FastDFS客户端上传文件方法
        ret = client.upload_by_buffer(file_bin)
        if ret['Status'] != 'Upload successed.':
            raise serializers.ValidationError('上传图片失败')

        # instance.name = validated_data['name'],
        # instance.first_letter = str(validated_data['first_letter']),
        # instance.logo = ret['Remote file_id']
        # instance.save()

        Brand.objects.filter(id=instance.id).update(
            name=validated_data['name'],
            first_letter=validated_data['first_letter'],
            logo=ret['Remote file_id']
        )

        return instance
